import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/mysql';
import { getCurrentUser } from '@/lib/auth';

export async function GET(request: NextRequest) {
  try {
    // 验证用户身份
    const user = getCurrentUser();
    if (!user || user.role !== 'admin') {
      return NextResponse.json(
        { success: false, error: '需要管理员权限' },
        { status: 403 }
      );
    }

    // 获取最近的用户注册
    const recentRegistrations = await query(
      `SELECT id, username, created_at 
       FROM users 
       ORDER BY created_at DESC 
       LIMIT 5`
    );

    // 获取最近的练习记录
    const recentSessions = await query(
      `SELECT ps.id, u.username, ps.topic_id, ps.correct_count, ps.question_count, ps.started_at
       FROM practice_sessions ps
       JOIN users u ON ps.user_id = u.id
       ORDER BY ps.started_at DESC
       LIMIT 5`
    );

    // 构建活动列表
    const activities = [];

    // 添加注册活动
    for (const user of recentRegistrations) {
      activities.push({
        id: `reg-${user.id}`,
        type: 'user_register',
        description: `新用户 "${user.username}" 注册成功`,
        timestamp: user.created_at,
        severity: 'info'
      });
    }

    // 添加练习活动
    for (const session of recentSessions) {
      const accuracy = session.question_count > 0
        ? Math.round((session.correct_count / session.question_count) * 100)
        : 0;
      
      activities.push({
        id: `session-${session.id}`,
        type: 'session_completed',
        description: `用户 "${session.username}" 完成练习，正确率 ${accuracy}%`,
        timestamp: session.started_at,
        severity: 'info'
      });
    }

    // 按时间排序
    activities.sort((a, b) => 
      new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
    );

    return NextResponse.json({
      success: true,
      data: activities.slice(0, 10) // 返回最近10条
    });

  } catch (error) {
    console.error('获取管理员活动数据错误:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: error instanceof Error ? error.message : '获取活动数据失败' 
      },
      { status: 500 }
    );
  }
}

